/**
 * Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
 * <p>
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springblade.modules.policy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springblade.common.constant.PolicyConstant;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.policy.entity.AuditRecord;
import org.springblade.modules.policy.entity.Policy;
import org.springblade.modules.policy.entity.PolicyDraw;
import org.springblade.modules.policy.service.IAuditRecordService;
import org.springblade.modules.policy.service.IPolicyDrawService;
import org.springblade.modules.policy.service.IPolicyService;
import org.springblade.modules.policy.vo.PolicyVO;
import org.springblade.modules.system.entity.City;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.entity.DictItem;
import org.springblade.modules.system.entity.File;
import org.springblade.modules.system.service.ICityService;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.IDictItemService;
import org.springblade.modules.system.service.IFileService;
import org.springblade.modules.system.vo.AvueUploadVo;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 控制器
 *
 * @author Blade
 * @since 2022-07-14
 */
@RestController
@AllArgsConstructor
@RequestMapping("/blade-policy/policy")
@Api(value = "", tags = "接口")
public class PolicyController extends BladeController {

	private IPolicyService policyService;

	private ICityService cityService;

	private IDeptService deptService;

	private IFileService fileService;

	private IAuditRecordService auditRecordService;

	private IPolicyDrawService policyDrawService;

	private IDictItemService dictItemService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入policy")
	public R<Policy> detail(Policy policy) {
		Policy detail = policyService.getOne(Condition.getQueryWrapper(policy));
		PolicyVO policyVO = new PolicyVO();
		BeanUtils.copyProperties(detail, policyVO);
		if (Func.isNotEmpty(detail.getFiles())) {
			LambdaQueryWrapper<File> fileLambdaQueryWrapper = Wrappers.lambdaQuery();
			fileLambdaQueryWrapper.in(File::getId, (Object[]) detail.getFiles().split(","));
			List<AvueUploadVo> list = new ArrayList<>(16);
			List<File> list1 = fileService.list(fileLambdaQueryWrapper);
			list1.forEach(i -> {
				AvueUploadVo avueUploadVo = new AvueUploadVo();
				avueUploadVo.setValue(i.getId() + "");
				avueUploadVo.setLabel(i.getOriginal());
				list.add(avueUploadVo);
			});
			policyVO.setFileList(list);
		}
		LambdaQueryWrapper<PolicyDraw> queryWrapper = Wrappers.lambdaQuery();
		queryWrapper.like(PolicyDraw::getPolicys, detail.getId());
		policyVO.setPolicyDrawList(policyDrawService.list(queryWrapper));
		return R.data(policyVO);
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入policy")
	public R<IPage<Policy>> list(Policy policy, Query query) {
		LambdaQueryWrapper<Policy> queryWrapper=new LambdaQueryWrapper<>();
		queryWrapper.like(Func.isNotBlank(policy.getPolicyName()),Policy::getPolicyName,policy.getPolicyName());
		queryWrapper.eq(Func.isNotEmpty(policy.getAthletsLevelId()),Policy::getAthletsLevelId,policy.getAthletsLevelId());
		queryWrapper.eq(Func.isNotBlank(policy.getLevelName()),Policy::getLevelName,policy.getLevelName());
		queryWrapper.like(Func.isNotBlank(policy.getDeptName()),Policy::getDeptName,policy.getDeptName());
		IPage<Policy> pages = policyService.page(Condition.getPage(query),queryWrapper);
		return R.data(pages);
	}

	/**
	 * 自定义分页
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入policy")
	public R<IPage<PolicyVO>> page(PolicyVO policy, Query query) {
		IPage<PolicyVO> pages = policyService.selectPolicyPage(Condition.getPage(query), policy);
		return R.data(pages);
	}

	/**
	 * 自定义分页
	 */
	@GetMapping("/pageAudit")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "审核分页", notes = "传入policy")
	public R<IPage<Policy>> pageAudit(PolicyVO policy, Query query) {
			LambdaQueryWrapper<Policy> queryWrapper = Wrappers.lambdaQuery();
			queryWrapper.eq(Func.isNotBlank(policy.getPolicyName()), Policy::getPolicyName, policy.getPolicyName());
			queryWrapper.eq(policy.getAthletsLevelId() != null, Policy::getAthletsLevelId, policy.getAthletsLevelId());
			if (policy.getPublishStatus() != null) {
				queryWrapper.eq(Policy::getPublishStatus, policy.getPublishStatus());
			} else {
				queryWrapper.eq(Policy::getPublishStatus, PolicyConstant.POLICY_PUBLISH_STATUS_WAIT_CHECK);
				queryWrapper.or().eq(Policy::getPublishStatus, PolicyConstant.POLICY_PUBLISH_STATUS_CHECK_FAIL);
				queryWrapper.or().eq(Policy::getPublishStatus, PolicyConstant.POLICY_PUBLISH_STATUS_CHECK_PASS);
			}
			IPage<Policy> pages = policyService.page(Condition.getPage(query), queryWrapper);
			return R.data(pages);
	}

	/**
	 * 自定义分页
	 */
	@GetMapping("/page/draw")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入policy")
	public R<IPage<Policy>> pagePolicy(PolicyVO policy, Query query) {
		LambdaQueryWrapper<Policy> lambdaQueryWrapper = Wrappers.lambdaQuery();
		lambdaQueryWrapper.eq(policy.getId() != null, Policy::getId, policy.getId());
		lambdaQueryWrapper.like(Func.isNotBlank(policy.getPolicyName()), Policy::getPolicyName, policy.getPolicyName());
		IPage<Policy> pages = policyService.page(Condition.getPage(query), lambdaQueryWrapper);
		return R.data(pages);
	}

	/**
	 * 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入policy")
	public R save(@Valid @RequestBody Policy policy) {
		policy.setPublishStatus(PolicyConstant.POLICY_PUBLISH_STATUS_WAIT_SUBMIT);
		return R.status(policyService.save(policy));
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入policy")
	public R update(@Valid @RequestBody Policy policy) {
		return R.status(policyService.updateById(policy));
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入policy")
	public R submit(@Valid @RequestBody PolicyVO policyVO) {
		Policy policy = new Policy();
		BeanUtils.copyProperties(policyVO, policy);
		policy.setPublishStatus(PolicyConstant.POLICY_PUBLISH_STATUS_WAIT_SUBMIT);
		LambdaQueryWrapper<City> cityWrapper = Wrappers.lambdaQuery();
		cityWrapper.eq(City::getRegionCode, policy.getLevelId());
		City one = cityService.getOne(cityWrapper);
		policy.setLevelName(one.getAbbreviation());
		if (policy.getAthletsOrgId() != null && policy.getAthletsOrgId() > 0) {
			Dept byId = deptService.getById(policy.getAthletsOrgId());
			policy.setAthletsOrgName(byId.getDeptName());
			policy.setAthletsOrg(byId.getDeptName());
		}else {
			policy.setAthletsOrgName(policyVO.getAthletsOrg());
		}
		return R.status(policyService.saveOrUpdate(policy));
	}


	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(policyService.deleteLogic(Func.toLongList(ids)));
	}

	/*
		政策状态修改
	 */
	@GetMapping("/change/{id}")
	public R changeStatus(@RequestParam String option, @PathVariable Long id) {

		Policy byId = policyService.getById(id);
		if (option.equals("sub")) {
			if (byId.getPublishStatus() >= PolicyConstant.POLICY_PUBLISH_STATUS_WAIT_CHECK) {
				return R.fail("政策已提交");
			} else {
				byId.setPublishStatus(PolicyConstant.POLICY_PUBLISH_STATUS_WAIT_CHECK);
			}
		} else if (option.equals("push")) {
			if (byId.getPublishStatus() > PolicyConstant.POLICY_PUBLISH_STATUS_CHECK_PASS) {
				return R.fail("政策已发布");
			} else if (byId.getPublishStatus() < PolicyConstant.POLICY_PUBLISH_STATUS_CHECK_PASS) {
				return R.fail("政策未审核通过");
			}
			if (byId.getEndTime().equals("长期有效")) {
				byId.setPublishStatus(PolicyConstant.POLICY_PUBLISH_STATUS_LONGTIME);
			} else {
				byId.setPublishStatus(PolicyConstant.POLICY_PUBLISH_STATUS_PROCESSING);
			}
			byId.setPublishTime(new Date());
		} else if (option.equals("unPush")) {
			if (byId.getPublishStatus() < PolicyConstant.POLICY_PUBLISH_STATUS_PROCESSING) {
				return R.fail("政策未发布");
			} else if (byId.getPublishStatus() > PolicyConstant.POLICY_PUBLISH_STATUS_LONGTIME) {
				return R.fail("政策已结束");

			} else {
				byId.setPublishStatus(PolicyConstant.POLICY_PUBLISH_STATUS_CHECK_PASS);
				byId.setPublishTime(null);
			}
		}
		return R.status(policyService.updateById(byId));

	}

	/*
	政策审核通过
	 */
	@GetMapping("/pass/{id}")
	public R pass(@PathVariable Long id) {
		Policy byId = policyService.getById(id);
		byId.setPublishStatus(PolicyConstant.POLICY_PUBLISH_STATUS_CHECK_PASS);
		return R.status(policyService.updateById(byId));
	}
	/*
	政策审核驳回
	 */
	@PostMapping("/reject")
	public R reject(@RequestBody AuditRecord auditRecord) {
		if (auditRecordService.save(auditRecord)) {
			Policy byId = policyService.getById(auditRecord.getAuditId());
			byId.setPublishStatus(PolicyConstant.POLICY_PUBLISH_STATUS_CHECK_FAIL);
			return R.status(policyService.updateById(byId));
		} else {
			return R.fail("操作失败");
		}

	}

	/*
	政策统计
	 */
	@GetMapping("/handleStatisticsAll")
	public R handleStatisticsAll(Policy policy) {
		Map<String, Long> map = new ConcurrentHashMap<>(16);
		QueryWrapper<Policy> queryWrapper1 = Condition.getQueryWrapper(policy);
		long allCount = policyService.count(queryWrapper1);
		queryWrapper1.le("publish_status", PolicyConstant.POLICY_PUBLISH_STATUS_CHECK_PASS)
			.or()
			.eq("publish_status", PolicyConstant.POLICY_PUBLISH_STATUS_END);
		long unPush = policyService.count(queryWrapper1);
		QueryWrapper<Policy> queryWrapper2 = Condition.getQueryWrapper(policy);
		queryWrapper2.gt("publish_status", PolicyConstant.POLICY_PUBLISH_STATUS_CHECK_PASS);
		queryWrapper2.ne("publish_status", PolicyConstant.POLICY_PUBLISH_STATUS_END);
		long push = policyService.count(queryWrapper2);
		map.put("all", allCount);
		map.put("unPush", unPush);
		map.put("push", push);
		return R.data(map);
	}
	@GetMapping("/selectPolicyCount")
	public R selectPolicyCount(){
		List<Map> PolicyCountList=policyService.selectPolicyCount();
		for (Map p:PolicyCountList
			 ) {
			p.replace("name",dictItemService.getLabel("place_id",p.get("name").toString()));
		}
		return R.data(PolicyCountList);
	}
}
